<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="表单" prop="formId">
        <el-select v-model="queryParams.formId" placeholder="请选择表单" clearable size="small">
          <el-option
            v-for="item in formList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="showData"
          v-hasPermi="['activiti:actMaintainOrderData:add']"
        >自定义列</el-button>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['activiti:actMaintainOrderData:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['activiti:actMaintainOrderData:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['activiti:actMaintainOrderData:export']"
          >导出</el-button>
        </el-col>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="actMaintainOrderDataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="表单id" align="center" prop="formId" />
      <!--<el-table-column label="表单值" align="center" prop="formVariables" />-->
      <!--<el-table-column label="表单类型" align="center" prop="formType" />-->
      <!--<el-table-column label="表单项的数组" align="center" prop="fields" />-->
      <!--<el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column v-for="col in cols" :label="col.label" align="center" :key="col.prop" :prop="col.prop">
      </el-table-column>
      <!--<el-table-column label="编码" align="center" prop="desfromCode" />-->
      <!--<el-table-column label="名称" align="center" prop="desfromName" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateData(scope.row)"
            v-hasPermi="['activiti:actMaintainOrderData:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['activiti:actMaintainOrderData:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--表单配置详情-->
    <el-dialog title="表单数据修改" :visible.sync="detailOpen" width="50%" append-to-body>
      <div class="test-form">
        <parser :key="new Date().getTime()" :form-conf="detailForm"  @submit="submitDetailForm" />
      </div>
    </el-dialog>
    <!-- 自定义列 -->
    <el-dialog title="选择需要展示的字段" :visible.sync="dialogFormVisible" width="40%" center top='15vh'>
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0;"></div>
      <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
        <el-checkbox v-for="item in cities" :label="item.prop" :key="item.prop"> {{item.label}}</el-checkbox>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible=false" size='medium'>取 消</el-button>
        <el-button type="primary" @click="confirmShow" size='medium'>确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改维护单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="编码" prop="desfromCode">
          <el-input v-model="form.desfromCode" placeholder="请输入编码" />
        </el-form-item>
        <el-form-item label="名称" prop="desfromName">
          <el-input v-model="form.desfromName" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listActMaintainOrder, getActMaintainOrder, delActMaintainOrder, addActMaintainOrder, updateActMaintainOrder,
    }from "@/api/system/activiti/actMaintainOrder";
  import { listActMaintainOrderData, getActMaintainOrderData, getActMaintainOrderDataVO,delActMaintainOrderData, addActMaintainOrderData,
    updateActMaintainOrderData,updateActMaintainOrderDataVO } from "@/api/system/activiti/actMaintainOrderData";
  //const cityOptions = ['date', 'name', 'address']; //所有的数据
  import Parser from '@/components/parser/Parser';
  import {getActMaintainOrderCols } from "@/views/system/activiti/formDataQuery/formDataQuery"
  export default {
    name: "ActMaintainOrder",
    components: {
      Parser
    },
    data() {
      return {
        cityOptions:[],
        checkAll: true,  //默认全选
        checkedCities: [], //默认全选所有的数据
        cities: [],   //对象数组全部的数据
        isIndeterminate: false,   //默认全选
        dialogFormVisible: false,
        // 维护单表格数据
        actMaintainOrderDataList: [],
        cols: [],
        tempCols: [],  //临时的数据容器
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        formList:[],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 表单详情
        detailOpen: false,
        detailForm: {
          fields: []
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          formId: null,
          formType: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          // desfromCode:[{ required: true, message: "编码不能为空", trigger: "blur" }],
          // desfromName:[{ required: true, message: "名称不能为空", trigger: "blur" }],
        }
      };
    },
    created() {
      listActMaintainOrder().then(response => {
        this.formList = response.rows;
        this.queryParams.formId = this.formList[0].id;
        this.handleQuery();
      });
      // getActMaintainOrderCols(this.queryParams.formId).then(response => {
      //   this.cities = response.data;
      // });
      //this.getList();

    },
    methods: {
      //全选按钮
      handleCheckAllChange(val) {
        this.checkedCities = val ? this.cityOptions : [];
        this.isIndeterminate = false;
      },
      //单个选中
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.cities.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
      },
      showData(row) {
        this.dialogFormVisible = true;
      },
      confirmShow() {
        this.tempCols = [];
        if (this.checkedCities.length < 1) {
          this.$message.warning("请至少选择一项数据");
          this.dialogFormVisible = true;
        } else {
          for (var i = 0; i < this.cities.length; i++) {
            for (var j = 0; j < this.checkedCities.length; j++) {
              if (this.cities[i].prop == this.checkedCities[j]) {
                this.tempCols.push(this.cities[i]);
              }
            }
          }
          this.cols = this.tempCols;
          this.dialogFormVisible = false;
        }
      },
      /** 查询维护单列表 */
      getList() {
        this.loading = true;
        listActMaintainOrderData(this.queryParams).then(response => {
          this.actMaintainOrderDataList = response.rows;
          this.actMaintainOrderDataList.forEach(item=>{
            let obj = JSON.parse(item.formVariables);
            item.formVariables='';
            let newJSON = Object.assign(item,obj)
            item = newJSON;
          })
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          desfromCode: null,
          desfromName: null,
          desfromJson: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        getActMaintainOrderCols(this.queryParams.formId).then(response => {
          this.cities = response.data;
          this.checkedCities = [];
          this.cities.forEach(item=>{
            this.checkedCities.push(item.prop);
          })
          this.cols = JSON.parse(JSON.stringify(this.cities)); //深拷贝
          //this.confirmShow();
          this.getList();
        });

      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加维护单";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getActMaintainOrder(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改维护单";
        });
      },
      handleUpdateData(row){
        this.reset();
        this.form.id=row.id;
        //formId,预览
        const id = row.id || this.ids
        getActMaintainOrderDataVO(id).then(response => {
          // 设置值
          const data = response.data;
          this.detailForm = {
            ...JSON.parse(data.formConf),
            fields: decodeFields(data.formFields),
            formId:row.formId
          }

        // 设置表单的值
        this.detailForm.fields.forEach(item => {
          const val = data.formVariables[item.__vModel__]
          if (val) {
            item.__config__.defaultValue = val
          }
        });
        // 弹窗打开
        this.detailOpen = true
      });
      // getActMaintainOrder(row.formId).then(response => {
      //   // 设置值
      //   const data = response.data;
      //   this.detailForm = {
      //     ...JSON.parse(data.conf),
      //     fields: decodeFields(data.fields),
      //     formId:row.formId
      //   }
      //   // 弹窗打开
      //   this.detailOpen = true
      // })

    },
    submitDetailForm(params){
      if (!params) {
        return;
      }
      // 设置表单禁用
      const conf = params.conf;
      conf.disabled = true; // 表单禁用
      conf.formBtns = false; // 按钮隐藏
      // 提交表单，创建流程
      const variables = params.values;
      console.log("form: " + variables);
      updateActMaintainOrderDataVO({
        id:this.form.id,
        formId: params.formId,
        formVariables: variables
      }).then(response => {
        this.msgSuccess("修改表单数据成功");
        // 关闭当前窗口
        // this.$tab.closeOpenPage();
        // this.$router.go(-1);
        this.detailOpen = false;
      }).catch(() => {
        conf.disabled = false; // 表单开启
        conf.formBtns = true; // 按钮展示
      })
    },
    /** 提交按钮 */
      submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateActMaintainOrderData(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addActMaintainOrderData(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
      handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除表单数据编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delActMaintainOrderData(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
      handleExport() {
      this.download('activiti/actMaintainOrderData/export', {
        ...this.queryParams
      }, `activiti_actMaintainOrderData.xlsx`)
    }
  }
};
</script>
